package com.deyang.mycommon.mvp.presenter;

import android.app.Activity;

import com.deyang.mycommon.entity.BaseResponse;
import com.deyang.mycommon.entity.Phone;
import com.deyang.mycommon.mvp.view.PhoneAddressView;
import com.deyang.mycommon.service.IHttpService;
import com.deyang.mycommon.util.Logger;
import com.deyang.mycommon.util.RetrofitUtil;
import com.deyang.mycommon.util.StringUtil;
import com.deyang.mycommon.util.ToastUtil;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * mvp  p   负责逻辑的处理
 */
public class PhoneAddressPresenter extends BasePresenter {

    private static final String TAG = "PhoneAddressPresenter";

    public Activity activity;

    private PhoneAddressView phoneAddressView;

    private Phone phone;

    private IHttpService httpService;


    public Phone getPhone() {
        return phone;
    }

    public PhoneAddressPresenter(Activity activity, PhoneAddressView phoneAddressView) {
        this.phoneAddressView = phoneAddressView;
        RetrofitUtil retrofitUtil = new RetrofitUtil(activity);
        this.activity = activity;
        httpService = retrofitUtil.getHttpService();
    }

    /**
     * 查询手机 归属地
     *
     * @param phone
     */
    public void seachPhoneInfo(String phone) {
        if (!StringUtil.isMobileNO(phone)) {
            ToastUtil.showWarning("手机号错误");
            return;
        }
        phoneAddressView.showLoading();
        requestSeachPhone(phone);
    }

    /**
     * 查询手机号码
     */
    private void requestSeachPhone(final String mPhone) {
        httpService.getPhoneInfo("45ce719c42fdb25e", mPhone)
                .subscribeOn(Schedulers.newThread())
                //最后在主线程中执行
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseResponse<Phone>>() {
                    @Override
                    public void onCompleted() {
                        phoneAddressView.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        phoneAddressView.hideLoading();
                    }

                    @Override
                    public void onNext(BaseResponse<Phone> s) {
                        phone = s.getResult();
                        phoneAddressView.updateView();
                        Logger.e(TAG, "res:" + s);
                    }
                });
    }

    @Override
    public void initData() {

    }
}
